package priv.mill.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateHandler {
	public static interface Handler {
		void doHandler(Session session) throws Exception;
	}

	private static Configuration configure;
	private static SessionFactory sessionFactory;
	private static StandardServiceRegistry serviceRegistry;

	public static void handlerSession(Handler handler) {
		 configure = new Configuration().configure("hibernate.cfg.xml");
		 serviceRegistry = new StandardServiceRegistryBuilder()
				.applySettings(configure.getProperties()).build();
		 sessionFactory = configure.buildSessionFactory(serviceRegistry);
		
		Session session = sessionFactory.openSession();
		try {
			handler.doHandler(session);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
//			session.close();
//			sessionFactory.close();
		}
		
	}
	
	public static void handlerCommit(Handler handler) {
		handlerSession(new Handler() {
			
			@Override
			public void doHandler(Session session) throws Exception {
				Transaction beginTransaction = session.beginTransaction();
				handler.doHandler(session);
				beginTransaction.commit();
			}
		});
	}
}
